# -*- coding: utf-8 -*-
from datetime import timedelta
from jms_daily_test.ods import jms_tmp__yl_lmdm_sys_area
from utils.alerts.doris_telnet_check import net_is_used
from utils.operators.rich_sql_sensor import RichSqlSensor

label = "doris_tmp__yl_lmdm_sys_area_{{ execution_date | cst_ds_nodash }}_{{ ti.try_number }}"
timeout = timedelta(minutes=10).seconds
dorisConn = net_is_used()
doris_tmp__yl_lmdm_sys_area = RichSqlSensor(
    task_id='doris_tmp__yl_lmdm_sys_area',
    email=['zhangqinglin@jtexpress.com','yl_bigdata@yl-scm.com'],
    pool='broker_load_pool',
    conn_id='doris',
    pre_sql=f"""
             TRUNCATE TABLE jms_dim.yl_lmdm_sys_area PARTITION (p{{{{ execution_date | cst_ds_nodash }}}});
             LOAD LABEL jms_dim.{label} (
                 DATA INFILE("hdfs://yl-bg-hdp/dw/hive/jms_tmp.db/external/yl_lmdm_sys_area/dt={{{{ execution_date | cst_ds }}}}/*")
                 INTO TABLE yl_lmdm_sys_area
                 FORMAT AS 'PARQUET'
                 (id,parent_id,country_id,code,international_code,three_code,type,cn_name,en_name,abbreviation,native_name,area_no,zipcode,longitude,latitude,is_enable,is_delete,create_by,update_by,create_by_name,update_by_name,create_time,update_time,version,sort,dtb_name,ad_code,no_district_flag)
                 SET (dt = DATE('{{{{ execution_date | cst_ds }}}}'))
             )
             WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
             PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dim WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dim WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

doris_tmp__yl_lmdm_sys_area << jms_tmp__yl_lmdm_sys_area
